#!/usr/bin/env bash
. pkg.sh
. cfg.sh
. log.sh

case $1 in
	auto)
		p=$(readlink -f $0)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if ! [ -d ${TREE_STUMP} ]; then
			$p init
			$p update db
		fi
		$p update conf
		if [ -z "$(ps -ef | grep 'job hook' | grep -v 'grep')" ]; then
			$p hook
		fi
	;;
	update)
		case "${2}" in
			db)
				_log info 'Updating database...'
				store_db
				update_db
				;;
			conf)
				_log info 'Updating config...'
				update_conf
				;;
		esac
	;;
	download)
		shift
		while [ $# -gt 0 ]; do
			D=""
			for i in ${@}; do
				shift
				D="${D} $(depends_pkg ${i})"
				! [ -z ${D} ] && _log info "${i} depends \x1b[1m${D}\x1b[m"
				P="$(lookup_pkg ${i})"
				if [ $? -ne 0 ]; then
					_log error "could not resolve: ${i}"
				else
					download_pkg ${P}
					[ $? -eq 0 ] && prepare_pkg $(echo ${P} | cut -s -f2 -d' ')
				fi
			done
			set -- ${D}
		done
	;;
	list)
		shift
		FILTER="${1}"
		while read -r line; do
			OUT=""
			set -- ${line}
			while [ $# -gt 0 ]; do
				case $(echo "${1}" | grep -oE "${FILTER}|--")  in
					'NEW')
						OUT="\x1b[32mN\x1b[00m  "
						;;
					'MOD')
						OUT=" \x1b[33mC\x1b[00m "
						;;
					'DEL')
						OUT="  \x1b[31mD\x1b[00m"
						;;
					'--')
						[ -z "${OUT}" ] && { shift; continue; }
						DIFF=$(expr 6 - $(echo ${OUT} | wc --bytes))
						printf '[%*b] %s\n' "${DIFF}" "${OUT}" "$(echo ${line} | cut -s -f3- -d'-')"
						;;
				esac
				
				shift
			done
		done < <(diff_db)
	;;
	hook)
		EVENT_FILE=$(grep ^EVENT_FILE ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if ! [ -z "${2}" ]; then

			while read -r line; do
				run_pkg $line $(date --rfc-3339=seconds | tr ' ' '_')
			done < <(grep "${2}" ./hooks.conf | cut -f2- -d' ')
			
			if ! [ "${2}" = "exit" ]; then
				$(readlink -f $0) hook
			fi
		else
			if [ $(stat -t ${EVENT_FILE} | cut -f2 -d' ') -ne 0 ]; then
				$(readlink -f $0) hook "$(sed -i -e '1{w /dev/stdout' -e 'd}' ${EVENT_FILE})";
			else
				{ watch -g stat ${EVENT_FILE} > /dev/null && { $(readlink -f $0) hook "$(sed -i -e '1{w /dev/stdout' -e 'd}' ${EVENT_FILE})"; };} &
			fi
		fi
	;;
	event)
		EVENT_FILE=$(grep ^EVENT_FILE ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if [ -z "${2}" ]; then
			touch ${EVENT_FILE}
		else
			echo "${2}" >> ${EVENT_FILE}
		fi
	;;
	init)
		while read -r line; do
			line=$(echo ${line} | cut -f2 -d'=' | sed 's/^"//;s/"$//')
			if [ "$(echo $line | cut -c1)" = "#" ]; then
				MODE="$(echo $line | cut -c2-)"
				continue
			fi

			
			case "${MODE}" in
				FOLDER)
					DIR=$(eval "echo ${line}")
					mkdir -p ${DIR} 2>&1 > /dev/null
				;;
				FILE)
					DIR=$(eval "echo ${line}")
					# TODO: Create file path?
					touch ${DIR} 2>&1 > /dev/null
				;;
				URL)
					break
				;;
			esac
			case $(ls -ld ${DIR} | cut -c1) in
				d)
					type=DIRECTORY
					;;
				-)
					type=FILE
					;;
			esac
			if [ $? -ne 0 ]; then
				_log error "cannot create ${type} ${DIR}" 2>/dev/null
			else
				_log success "created ${type} ${DIR}"
			fi
		done < paths.conf
	;;
	list)
		exit
		shift
		FMT="%10s %10 %20s\n"
		printf "${FMT}" "NAME" "REPO" "DEPENDS"
		while read -r repo; do
			while read -r line; do
				printf "${FMT}" $(basename ${repo}) ${line}
			done < ${repo}
		done < <(find ${REPO_STORE} -type f)
	;;
	deinit)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		echo ${TREE_STUMP}
		if ! [ -d ${TREE_STUMP} ]; then
			exit
		fi
		START=""
		while read -r line; do
			line=$(readlink -f ${line})
			if [ $(echo ${START} | wc --bytes) -lt $(echo ${line} | wc --bytes) ]; then
				START=${line}
			fi
		done < <(find ${TREE_STUMP})
		[ -f "${START}" ] && START=$(dirname ${START})

		while true; do
			while read -r l; do
				_log warn "deleting ${l}"
				rm -rf ${l}
			done < <(find ${START} -type d)
			START=$(dirname ${START})

			if [ ${START} = $(readlink -f ${TREE_STUMP}) ]; then
				break
			fi
		done
		while read -r l; do
			_log warn "deleting ${l}"
			rm -rf ${l}
		done < <(find ${START} -type d | sort -r)
	;;
esac
